package bb.lanxing.devices.config;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import bb.lanxing.lib.devices.base.DeviceServiceBinder;
import bb.lanxing.lib.devices.remote.IRemoteDeviceService;
import java.util.Iterator;
import java.util.LinkedList;

public class SimpleDeviceServiceBinder implements DeviceServiceBinder, IBinder.DeathRecipient {
    private static final String ACTION_DEVICE_SERVICE = "bb.lanxing.devices.service";
    private static final String PERMISSION_BIND = "bb.lanxing.devices.bind_service";
    private LinkedList<Runnable> boundTask;
    private IRemoteDeviceService mRemoveDeviceService;
    private final Object syncLock = new Object();

    @Override
    public void addBindTask(Runnable runnable) {
        synchronized (this.syncLock) {
            if (this.boundTask == null) {
                this.boundTask = new LinkedList<>();
            }
            this.boundTask.add(runnable);
        }
        if (isServiceBind()) {
            runBindTask();
        }
    }

    private void runBindTask() {
        synchronized (this.syncLock) {
            LinkedList<Runnable> linkedList = this.boundTask;
            if (linkedList != null && !linkedList.isEmpty()) {
                Iterator<Runnable> it = this.boundTask.iterator();
                while (it.hasNext()) {
                    Runnable next = it.next();
                    if (next != null) {
                        next.run();
                    }
                }
                this.boundTask.clear();
            }
        }
    }

    private boolean isServiceBind() {
        return this.mRemoveDeviceService != null;
    }

    @Override
    public void bindDeviceService(Context context) {
        if (isServiceBind()) {
            return;
        }
        Intent intent = new Intent(ACTION_DEVICE_SERVICE);
        intent.setPackage(context.getPackageName());
        context.bindService(intent, this, 1);
    }

    @Override
    public void unbindDeviceService(Context context) {
        if (!isServiceBind()) {
            return;
        }
        context.unbindService(this);
        this.mRemoveDeviceService = null;
    }

    @Override
    public IRemoteDeviceService getDeviceService() {
        return this.mRemoveDeviceService;
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        try {
            iBinder.linkToDeath(this, 0);
        } catch (RemoteException unused) {
        }
        this.mRemoveDeviceService = IRemoteDeviceService.Stub.asInterface(iBinder);
        runBindTask();
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        this.mRemoveDeviceService = null;
    }

    @Override
    public void binderDied() {
        this.mRemoveDeviceService = null;
    }
}
